package com.ellricky.tv.adapter

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.ellricky.baselib.entity.new.WareLearn
import com.ellricky.tv.R

class TvCourseAdapter2 : RecyclerView.Adapter<TvCourseAdapter2.ViewHolder>() {

    private var itemClick: ((position: Int) -> Unit)? = null
    var dataSource: List<WareLearn>? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.tv_item_course, parent, false)
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data = dataSource?.get(position) ?: return
        holder.bind(data)
        holder.itemView.setOnClickListener {
            itemClick?.invoke(position)
        }
    }

    override fun getItemCount(): Int {
        return dataSource?.size ?: 0
    }

    fun setData(list: List<WareLearn>) {
        this.dataSource = list
        notifyDataSetChanged()
    }

    fun setItemClickListener(block: (position: Int) -> Unit) {
        this.itemClick = block
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val mTempColor = arrayOf(
            "#C0E4E8", "#A2D7DE", "#9ED8F0", "#8BC1EA", "#83A2D3", "#688AAC", "#018699",
            "#02A3B1", "#2983A5", "#59B8C8", "#0095C5", "#4C6BA9", "#BDBBE2", "#887AAA", "#4C5AB0"
        )
        val tvName = view.findViewById<TextView>(R.id.tvName)
        val tvAge = view.findViewById<TextView>(R.id.tvAge)

        fun bind(entry: WareLearn) {
            tvName.text = entry.ware_name
            tvAge.text = entry.ware_sort
            val shapeDrawable = itemView.background
                    as GradientDrawable
            shapeDrawable.setColor(Color.parseColor(getBackgroundColor()))
        }

        private fun getBackgroundColor(): String {
            return mTempColor[(Math.random() * 10 + 4).toInt()]
        }
    }
}